#include "Socket.hpp"
#include "Protocol.hpp"
#include "Log.hpp"
#include <time.h>
#include <iostream>
#include <unistd.h>
using std:: cout;
using std:: cin;
using std:: endl;

int main()
{
    std::string server_ip = "120.53.91.43";
    uint16_t server_port = 8080;

    Socket sockfd;
    sockfd.Create();
    int success = sockfd.Connect(server_ip, server_port);
    if(!success == -1)
    {
        cout << "connect fail" << endl;
        exit(1);
    }

    srand((unsigned int)time(NULL));
    int cnt = 10;
    std::string ops = "+-*/";

    while(cnt--)
    {
        int x = rand()%100+1;
        usleep(1234);
        int y = rand()%100;
        usleep(1234);
        char op = ops[rand()%4];
        Request req(x, y, op);

        //发送请求
        std::string package;
        req.Serialize(&package);
        package = Encode(package);
        write(sockfd.GetSockfd(), package.c_str(), package.size());

        //接收响应
        char buffer[128];
        read(sockfd.GetSockfd(),buffer, sizeof(buffer));
        std::string respone_pack = buffer;
        //反序列化来提取结果
        Response resp;
        std::string content;
        bool success = Decode(respone_pack, &content);
        if(success)
        {
            resp.Deserialize(content);
            cout << x << op << y << " = ";
            cout << resp.result << "--状态码--" << resp.code << endl;
            sleep(1);
        }
    }

    return 0;
}

